import requests
from urllib.parse import quote
from collections import defaultdict
import random
from Config import GET_PROXY_IP_URL_TEMPLATE, IPCONFIG, VALID_IP_URL, MAX_RETRIES
from logging_config import configure_logger

# 使用 defaultdict(list) 来缓存代理 IP
proxy_cache = defaultdict(list)

logger = configure_logger()  # 使用配置好的日志记录器

def get_proxy_list(num='1'):
    url_format = IPCONFIG.copy()  # 假设 IPCONFIG 是一个字典
    url_format['num'] = str(num)
    get_proxy_ip_url = GET_PROXY_IP_URL_TEMPLATE.format(**url_format)
    response = requests.get(get_proxy_ip_url)
    if response.status_code == 200:
        result = response.json()
        return result['data']['proxy_list']
    else:
        raise Exception("获取不到代理IP...请联系供应商")


def valid_proxy(ip, username, password):
    proxies = {
        "http": f"http://{username}:{quote(password)}@{ip}/",
        "https": f"http://{username}:{quote(password)}@{ip}/"
    }
    try:
        response = requests.get(VALID_IP_URL, proxies=proxies, timeout=5)
        logger.info(f"代理状态码：{response.status_code}")
        if response.status_code not in [400, 460, 454]:
            return ip
        return False
    except Exception as e:
        logger.error(f"代理IP验证失败: {ip}, 错误: {str(e)}")
        return False


def get_proxy_from_cache(username, password):
    _retry_count = 0
    while _retry_count < 3:
        # 如果缓存中的代理数量不足 3 个，补充

        _proxy_list = get_proxy_list()
        for _ip in _proxy_list:
            proxy_cache['proxies'].append(_ip)

        # 获取当前缓存中的代理列表
        proxy_cache_list = proxy_cache['proxies']
        logger.info(f"当前缓存中的代理IP列表: {proxy_cache_list}")

        if not proxy_cache_list:
            break

        # 随机选择一个代理
        _cache_ip = random.choice(proxy_cache_list)
        if valid_proxy(_cache_ip, username, password):
            logger.info(f"成功获取可用代理IP: {_cache_ip}")
            proxy_cache['proxies'].remove(_cache_ip)
            return _cache_ip
        else:
            # 如果代理不可用，从缓存中移除
            proxy_cache['proxies'].remove(_cache_ip)
            _retry_count += 1

    logger.error("所有代理IP均不可用，重试次数已达上限")
    raise Exception("暂无可用ip,请联系供应商")


if __name__ == '__main__':
    ip = get_proxy_from_cache("d3404753001", "97wul9op")
    print("可用代理IP:", ip)